package com.servlet.user;

import com.entity.Code;
import com.service.UserService;
import com.utils.JsonUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/**
 * 根据用户ID修改密码。    在此之前，可以使用对FindPdId类发起请求，实时监测用户输入的密码是否正确，用户输入正确了。再请求这个
 * 必选参数：id、password、newpassword
 */
@WebServlet(name = "UpdateUserPd", value = "/UpdateUserPd")
public class UpdateUserPd extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        int id = Integer.parseInt(request.getParameter("id"));
        String oldpassword = request.getParameter("password");
        String newpassword = request.getParameter("newpassword");

        JsonUtil jsonUtil = new JsonUtil();
        UserService userService = new UserService();
        try {
            //通过IP查询数据库旧密码旧密码
            String password = userService.findPdById(id); //如果ID不存在，则返回用户ID不存在
            if (password.equals(oldpassword)){
                // 密码和数据库旧密码相等，则执行更新密码
                int i = userService.updateUserPd(newpassword, id);
                if (i==1){
                    //密码更换成功
                    Code code = new Code();
                    code.setCode("200");
                    code.setMsg("修改密码成功");
                    String s = jsonUtil.JavaToJson(code);
                    response.getWriter().print(s);
                }
            }else {
                // 密码不相等，返回403 密码不相等
                Code code = new Code();
                code.setCode("403");
                code.setMsg("密码错误");
                String s = jsonUtil.JavaToJson(code);
                response.getWriter().print(s);
            }
        }catch (Exception e){
            System.out.println("密码修改出现错误："+e);
            Code code = new Code();
            code.setCode("400");
            code.setMsg("该用户ID不存在");
            String s = jsonUtil.JavaToJson(code);
            response.getWriter().print(s);
        }


    }
}
